<template>
    <div class="e-form">
        <BillTop title="设备调动变更详情" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="调动明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="随机工具及技术资料" name="technicalInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.handoverTransfer" label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="调动编号：">
                                            <span>{{ formData.handoverTransfer.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="填报日期：">
                                            <span>{{formData.handoverTransfer.billDate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="经办人：">
                                            <span>{{formData.handoverTransfer.agenter}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="调入机构：">
                                            <span>{{formData.handoverTransfer.transferOrg}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="接收人：">
                                            <span>{{formData.handoverTransfer.receiver}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ statusLable(formData.handoverTransfer.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁金额（不含税）：">
                                            <span>{{ formData.handoverTransfer.amount }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="租赁金额（含税）：">
                                            <span>{{ formData.handoverTransfer.leaseAmount }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                <el-col :span="12">
                                        <el-form-item label="税率%：">
                                            <span>{{formData.handoverTransfer.tax}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="税额（元）：">
                                            <span>{{formData.handoverTransfer.taxAmount}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="机构：">
                                            <span>{{formData.handoverTransfer.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item  label="备注信息：">
                                        <span>{{formData.handoverTransfer.remarks}}</span>
                                    </el-form-item>
                                </el-row>
                                <el-row v-if="formData.handoverTransfer.state === 5">
                                        <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ formData.handoverTransfer.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{formData.handoverTransfer.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="formData.handoverTransfer.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                formData.handoverTransfer.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                formData.handoverTransfer.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">调动明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left"></div>
                                <div class="right">
                                    <div class="squarecolor">
                                        <div class="color colorAdd"></div>
                                        <span>新增</span>
                                    </div>
                                    <div class="squarecolor item">
                                        <div class="color colorUpdate"></div>
                                        <span>修改</span>
                                    </div>
                                    <div class="squarecolor">
                                        <div class="color colorDel"></div>
                                        <span>删除</span>
                                    </div>
                                </div>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="handoverTransferDtlListCopy"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClass"
                                v-sortTable="{ 'tableData': handoverTransferDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column prop="equipmentNo" label="设备编号" min-width="200" show-overflow-tooltip align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="originalNo"
                                    label="原始编号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    label="设备名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="categoryName"
                                    label="设备类别"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="100"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="manufacturer"
                                    label="生产厂商"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="originalPlace"
                                    label="原在何地"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="leaseUnit"
                                    label="计时单位"
                                    width="160"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="changeLeasePrice"
                                    width="180"
                                    align="right"
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后租金单价（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="changeLeaseTerm"
                                    width="180"
                                    align="center"
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后租赁时间<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="changeEnterPrice"
                                    width="180"
                                    align="right"
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后进场费（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="changeExitPrice"
                                    width="180"
                                    align="right"
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后退场费（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="changeOperatingSalary"
                                    width="200"
                                    align="right"
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后操作手工资（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leaseAmount"
                                    label="租赁金额（元）"
                                    width="130"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="maintenanceUnit"
                                    label="维修费承担方"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{['调出机构','调入机构'][row.maintenanceUnit]}}</span>
                                    </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="maintainUnit"
                                    label="保养费承担方"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{['调出机构','调入机构'][row.maintainUnit]}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="startTime"
                                    label="预计开始时间"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="handoverDate"
                                    label="交接日期"
                                    width="130"
                                    align="center"
                                    v-if="state === 2"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="验收情况"
                                    width="130"
                                    align="center"
                                    v-if="state === 2"
                                >
                                   <template slot-scope="{ row }">
                                        <el-button size="mini" class="btn-blue" @click="acceptCheck(row)"
                                            >查看</el-button
                                        >
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="technicalInfoCon" class="con">
                        <div class="tabs-title" id="technicalInfo">随机工具及技术资料</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="toolsTable"
                                :data="facilityAttachmentToolsListCopy"
                                border
                                style="width: 100%"
                                v-sortTable="{ 'tableData': facilityAttachmentToolsListCopy, '_this': this, 'ref': 'toolsTable' }"
                            >
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="name"
                                    align="center"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后名称<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="specifications"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                     <template slot="header">
                                        <div class="tab-header">变更后规格型号<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后计量单位<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="number"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后数量<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" isView bucketName="facilityconnect" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="40121"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.handoverTransfer.state" @exas="exas" :founderId="formData.handoverTransfer.founderId" />
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/purchaseAcceptance.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { getCurrentUnitInfo, history } from '@/api/equip/handoverAudit.js'
import { openAppClient, hideLoading } from '@/utils/common'
import { exas } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                //基础信息
                'handoverTransfer': {
                    'agenter': '',
                    'amount': null,
                    'auditDate': '',
                    'auditor': '',
                    'auditorId': '',
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'changeBillId': '',
                    'changeBillNo': '',
                    'changeState': 0,
                    'easId': '',
                    'founderId': '',
                    'founderName': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'leaseAmount': null,
                    'modifier': '',
                    'modifierId': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDescription': '',
                    'nullifyReason': '',
                    'number': null,
                    'orgId': '',
                    'orgName': '',
                    'receiver': '',
                    'recorder': '',
                    'recorderId': '',
                    'remarks': '',
                    'state': null,
                    'tax': null,
                    'taxAmount': null,
                    'transferOrg': '',
                    'transferOrgId': '',
                    'version': null,
                    'workId': ''
                }
            },
            billid: this.$route.query.billid,
            handoverTransferDtlList: [], //调动明细  传给后端
            handoverTransferDtlListCopy: [], //调动明细 前端显示
            planSelect: [], //调动明细选择项
            currentRow: {}, //调动明细当前行数据
            facilityAttachmentToolsList: [], //随机工具及技术资料 传后端
            facilityAttachmentToolsListCopy: [], //随机工具及技术资料 前端显示
            toolsSelect: [], //随机工具及技术资料选择项
            currentToolsRow: {}, //随机工具当前行数据
            auditHistoryTable: [], //审核历史表格
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 40121,
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 40121,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj ? obj.label : ''
            }
        },
        //当前单据状态
        state () {
            return this.formData.handoverTransfer.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.getDicValue()
        this.userId = localStorage.getItem('userId')
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'technicalInfo',  'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations([ 'setAuditParams']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //初始化数据
        init () {
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getTechnicalList(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()
            ]).finally(() => {
                hideLoading()
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //基本信息查询
        getInfo () {
            request.getEquipMoveBaseInfoChange(this.billid).then(res=>{
                this.formData.handoverTransfer = res
            })
        },
        //获取设备调动明细查询
        getPlanList () {
            request.getEquipMovePlanInfoChange(this.billid).then(res=>{
                this.handoverTransferDtlListCopy = []
                this.handoverTransferDtlList = res
                res.map(item=>{
                    this.handoverTransferDtlListCopy.push(item)
                })
            })
        },
        //获取随机工具及技术资料
        getTechnicalList () {
            request.getEquipMoveTechnicalChange(this.billid).then(res=>{
                this.facilityAttachmentToolsListCopy = []
                this.facilityAttachmentToolsList = res
                res.map(item=>{
                    this.facilityAttachmentToolsListCopy.push(item)
                })
            })
        },
        //验收情况
        acceptCheck (row) {
            this.setAuditParams({ id: row.receiveId })
            // 客户端弹窗弹出本地页面
            openAppClient('/equipMoveAttachShow', '附件查看')
        },
        //修改行样式
        tableRowClass ({ row }) {
            if(row.state == -1) {
                if(!row.sourcerId) {
                    return  'row-hide'
                }else{
                    return 'red'
                }
            }else if(row.state == 1) {
                return 'green'
            }else if(row.state == 2) {
                return 'yellow'
            }
            return ''
        },
        //取消
        handleClose () {
            this.$router.replace('/equipMoveList')
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 1)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}
.e-table {
    background: #fff;
}
</style>
